<template>
	<view class="container">
		<!-- 文章内容部分 -->
		<view class="article-header">
			<text class="title">{{ formatTitle(getTitle()) }}</text>
			<view class="meta">
				<text class="date">{{ formatDate(article.date) }}</text>
			</view>
		</view>

		<view class="article-content">
			<rich-text class="content" :nodes="formatContent(getContent())"></rich-text>


			<!-- 下载部分 -->
			<!-- <view class="download-section" v-if="downloadUrls.length">
        <view class="download-title">资源获取</view>
        <view class="download-btn" @tap="showDownloadOptions">
          <uni-icons type="download" size="18" color="#fff"></uni-icons>
          <text>选择下载链接</text>
        </view> -->

			<view class="download-section" v-if="downloadUrls.length || allLinks.length">
				<view class="download-title">资源获取</view>
				<view class="buttons-container">
					<view class="download-btn" @tap="showDownloadOptions" v-if="downloadUrls.length">
						<uni-icons type="download" size="18" color="#fff"></uni-icons>
						<text>选择下载链接</text>
					</view>
					<view class="download-btn all-links-btn" @tap="showAllLinks" v-if="allLinks.length">
						<uni-icons type="link" size="18" color="#fff"></uni-icons>
						<text>查看所有链接</text>
					</view>
				</view>
				<view class="disclaimer">
					<view class="disclaimer-title">声明：</view>
					<view class="disclaimer-item">1. 转载请保留原文链接，谢谢！</view>
					<view class="disclaimer-item">2. 本站所有资源文章出自互联网收集整理，本站不参与制作，如果侵犯了您的合法权益，请联系本站我们会及时删除。</view>
				</view>
			</view>
		</view>

		<view class="loading-box" v-if="loading">
			<view class="loading">
				<view class="loading-spinner"></view>
				<text>加载中...</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				article: {
					title: {
						rendered: ''
					},
					content: {
						rendered: ''
					},
					date: ''
				},
				loading: true,
				downloadUrls: [], // 存储所有匹配到的下载链接
				allLinks: [], // 存储所有超链接
			}
		},
		onLoad(options) {
			if (options.id) {
				this.getArticleDetail(options.id)
			}
		},
		methods: {
			async getArticleDetail(id) {
				this.loading = true
				try {
					const res = await uni.request({
						url: `https://lzphy.top/wp-json/wp/v2/posts/${id}`,
					})

					if (res && res.data) {
						this.article = res.data
						// 提取下载链接（支持夸克网盘和百度网盘）
						const downloadMatches = this.getContent().match(/href="([^"]*)"[^>]*>(夸克网盘|百度网盘)<\/a>/g)
						if (downloadMatches) {
							this.downloadUrls = downloadMatches.map(item => {
								const urlMatch = item.match(/href="([^"]*)"/)
								return urlMatch ? urlMatch[1] : ''
							})
						}
						// 提取所有链接并处理特殊链接
						const linkMatches = this.getContent().match(/href="([^"]*)"/g)
						if (linkMatches) {
							this.allLinks = linkMatches.map(item => {
								const urlMatch = item.match(/href="([^"]*)"/)
								const url = urlMatch ? urlMatch[1] : ''

								// 检查是否以 https://lzphy.top/ 开头且后面还有内容
								if (url.match(/^https:\/\/lzphy\.top\/.+/)) {
									return 
								}
								return url
							}).filter(url => url) // 过滤掉空链接
						}
					} else {
						throw new Error('文章数据获取失败')
					}
				} catch (e) {
					console.error('获取文章详情错误:', e)
					uni.showToast({
						title: '获取文章失败',
						icon: 'none'
					})
				} finally {
					this.loading = false
				}
			},

			showDownloadOptions() {
			  if (this.downloadUrls.length > 1) {
			    uni.showActionSheet({
			      // 在选项列表最后添加推广链接
			      itemList: [
			        ...this.downloadUrls.map(url => `复制链接: ${url}`),
			        '更多文章: https://lzphy.top/'
			      ],
			      success: (res) => {
			        // 判断是否点击的是推广链接
			        if (res.tapIndex === this.downloadUrls.length) {
			          this.copyToClipboard('https://lzphy.top/')
			        } else {
			          const selectedUrl = this.downloadUrls[res.tapIndex]
			          this.copyToClipboard(selectedUrl)
			        }
			      },
			      fail: (err) => {
			        console.error('操作失败', err)
			      }
			    })
			  } else if (this.downloadUrls.length === 1) {
			    uni.showActionSheet({
			      itemList: [
			        `复制链接: ${this.downloadUrls[0]}`,
			        '更多文章: https://lzphy.top/'
			      ],
			      success: (res) => {
			        if (res.tapIndex === 0) {
			          this.copyToClipboard(this.downloadUrls[0])
			        } else {
			          this.copyToClipboard('https://lzphy.top/')
			        }
			      }
			    })
			  }
			},
			showAllLinks() {
			  if (this.allLinks.length > 0) {
			    uni.showActionSheet({
			      // 在选项列表最后添加推广链接
			      itemList: [
			        ...this.allLinks.map(url => `复制链接: ${url.substring(0, 30)}...`),
			        '更多文章: https://lzphy.top/'
			      ],
			      success: (res) => {
			        // 判断是否点击的是推广链接
			        if (res.tapIndex === this.allLinks.length) {
			          this.copyToClipboard('https://lzphy.top/')
			        } else {
			          const selectedUrl = this.allLinks[res.tapIndex]
			          this.copyToClipboard(selectedUrl)
			        }
			      },
			      fail: (err) => {
			        console.error('操作失败', err)
			      }
			    })
			  } else {
			    uni.showToast({
			      title: '没有找到链接',
			      icon: 'none'
			    })
			  }
			},
			copyToClipboard(url) {
				uni.setClipboardData({
					data: url,
					success: () => {
						uni.showToast({
							title: '下载链接已复制',
							icon: 'success'
						})
					}
				})
			},

			getTitle() {
				return this.article?.title?.rendered || ''
			},

			getContent() {
				return this.article?.content?.rendered || ''
			},

			formatTitle(title) {
				if (!title) return ''
				return title.replace(/&#8211;/g, '-')
					.replace(/&amp;/g, '&')
					.replace(/&#8220;/g, '"')
					.replace(/&#8221;/g, '"')
					.replace(/&#8216;/g, "'")
					.replace(/&#8217;/g, "'")
			},
			formatContent(content) {
				if (!content) return ''
				// 处理HTML元素样式
				const styles = {
					img: 'max-width:100%;height:auto;display:block;margin:20rpx auto;',
					h2: 'font-size:36rpx;font-weight:bold;margin:40rpx 0 20rpx;color:#333;',
					a: 'color:#007AFF;text-decoration:none;',
					pre: 'background:#f5f6f7;padding:20rpx;margin:20rpx 0;border-radius:8rpx;font-family:Consolas,Monaco,monospace;font-size:24rpx;line-height:1.6;overflow-x:auto;white-space:pre-wrap;word-break:break-all;color:#333;',
					code: 'display:block;width:100%;background:#f5f6f7;',
					p: 'margin:16rpx 0;line-height:1.8;',
					ul: 'padding-left:40rpx;margin:16rpx 0;',
					ol: 'padding-left:40rpx;margin:16rpx 0;',
					li: 'margin:8rpx 0;'
				};

				// 应用样式
				Object.entries(styles).forEach(([tag, style]) => {
					content = content.replace(
						new RegExp(`<${tag}(?![^>]*style=)`, 'gi'),
						`<${tag} style="${style}"`
					);

					// 为已有style的标签添加额外样式
					content = content.replace(
						new RegExp(`<${tag}([^>]*?)style="([^"]*?)"`, 'gi'),
						`<${tag}$1style="$2;${style}"`
					);
				});

				return content;

			},

			formatDate(date) {
				if (!date) return ''
				const d = new Date(date)
				return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
			},
		}
	}
</script>

<style>
	.container {
		padding: 30rpx;
		background: #fff;
		min-height: 100vh;
	}

	.article-header {
		margin-bottom: 40rpx;
	}

	.title {
		font-size: 40rpx;
		font-weight: bold;
		color: #333;
		line-height: 1.4;
		margin-bottom: 20rpx;
	}

	.meta {
		display: flex;
		align-items: center;
	}

	.date {
		font-size: 24rpx;
		color: #999;
	}

	.content {
		font-size: 30rpx;
		line-height: 1.8;
	}
.buttons-container {
  display: flex;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.download-btn {
  flex: 1;
}

.all-links-btn {
  background: #28a745;
}
	.download-section {
		margin-top: 60rpx;
		padding: 30rpx;
		background: #f8f9fa;
		border-radius: 12rpx;
	}

	.download-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
	}

	.download-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		background: #007AFF;
		color: #fff;
		padding: 20rpx;
		border-radius: 8rpx;
		font-size: 28rpx;
	}

	.download-btn text {
		margin-left: 10rpx;
	}

	.loading-box {
		padding: 40rpx 0;
		text-align: center;
	}

	.loading {
		display: inline-flex;
		align-items: center;
	}

	.loading-spinner {
		width: 40rpx;
		height: 40rpx;
		border: 4rpx solid #f3f3f3;
		border-top: 4rpx solid #007AFF;
		border-radius: 50%;
		margin-right: 16rpx;
		animation: spin 1s linear infinite;
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}

	.loading text {
		font-size: 28rpx;
		color: #999;
	}

	.disclaimer {
		margin-top: 30rpx;
		padding-top: 30rpx;
		border-top: 1rpx solid #eee;
	}

	.disclaimer-title {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 16rpx;
	}

	.disclaimer-item {
		font-size: 24rpx;
		color: #666;
		line-height: 1.6;
		margin-bottom: 12rpx;
		text-align: justify;
	}

	/* 代码块样式 */
	.code-block {
		background: #f5f6f7;
		padding: 20rpx;
		margin: 20rpx 0;
		border-radius: 8rpx;
		font-family: Consolas, Monaco, 'Andale Mono', monospace;
		font-size: 24rpx;
		line-height: 1.6;
		overflow-x: auto;
		white-space: pre;
		word-wrap: normal;
		color: #333;
	}

	/* 代码行号样式 */
	/* 代码块样式 */
	pre code {
		background: #f5f6f7;
		padding: 20rpx;
		border-radius: 8rpx;
		font-family: Consolas, Monaco, 'Andale Mono', monospace;
		font-size: 28rpx;
		line-height: 1.6;
		overflow-x: auto;
		white-space: pre-wrap;
		word-break: break-all;
		color: #333;
	}

	.code-block code {
		display: block;
		width: 100%;
	}

	/* 代码行号样式 */
	.code-block .line-numbers {
		counter-reset: line;
		padding-left: 3em;
		position: relative;
	}

	.code-block .line-numbers>span {
		counter-increment: line;
		position: relative;
	}

	.code-block .line-numbers>span::before {
		content: counter(line);
		position: absolute;
		left: -3em;
		width: 2.5em;
		text-align: right;
		color: #999;
		padding-right: 0.5em;
		border-right: 1px solid #ddd;
	}
</style>